import 'package:eleapp/pages/photo/photo.dart';
import 'package:eleapp/res/strings.dart';
import 'package:eleapp/widget/emptydata.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../dio/http_request.dart';
import '../../dio/api.dart';

// import 'package:jac_uikit/common.dart';
import 'package:jac_uikit/data_display.dart';
// import 'package:jac_uikit/data_entry.dart';
// import 'package:jac_uikit/generated/assets.dart';

class Grouplist extends StatefulWidget {
  // 使用getx管理不用定义 arguments，直接Get.arguments获取传值
  // final Map arguments;
  // const Grouplist({super.key, required this.arguments});

  const Grouplist({super.key});

  @override
  State<Grouplist> createState() => _GrouplistState();
}

class _GrouplistState extends State<Grouplist> {
  List groupList = [];
  String taskname = '基础实训';
  int lessonId = 0;

  bool isReady = false;

  _load() async {
    List listRes = await Request2.post<List>(
        Api.practicegrouplist, {'lesson_id': Get.arguments['lesson_id']});

    for (int i = 0; i < listRes.length; i++) {
      Map params = {
        'lesson_id': listRes[i]['lesson_id'],
        'group_id': listRes[i]['id'],
      };
      Map evaluateRes = await Request2.post<Map>(Api.evaluatedetail, params,
          success: (evaluateRes) {});

      listRes[i]['isevaluate'] = evaluateRes.isNotEmpty;
      listRes[i]['tips'] = evaluateRes.isNotEmpty
          ? StringStyles.checkscore.tr
          : StringStyles.goscore.tr;
    }
    setState(() {
      isReady = true;
      groupList = listRes;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    print('Get.arguments');
    print(Get.arguments);

    Future.delayed(
      Duration.zero,
      () => setState(() {
        taskname = Get.arguments['lesson_name'];
        lessonId = Get.arguments['lesson_id'];
        _load();
      }),
    );
  }

  loadTaskGroup(List data) {
    List<Widget> treeList = [];
    for (int i = 0; i < data.length; i++) {
      treeList.add(Stack(
        // alignment: Alignment.center,
        children: [
          Card(
            shadowColor: Colors.black, // 阴影颜色
            elevation: 10, // 阴影值的深度（扩散度）
            // color: Colors.red, // 卡片颜色
            margin: EdgeInsets.only(
                top: 30,
                left: 15,
                right: 15,
                bottom: (i == data.length - 1) ? 30 : 0),
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(20))), // 影响卡片圆角
            clipBehavior: Clip.hardEdge,
            child: Column(
              children: [
                ListTile(
                  leading: Container(
                    height: 50,
                    width: 50,
                    color: Colors.black12,
                    child: const Icon(
                      Icons.group_rounded,
                      size: 36,
                    ),
                  ),
                  title: Text("${data[i]['title']}"),
                  subtitle:
                      Text("${StringStyles.groupNum.tr}：${data[i]['sn']}"),
                  trailing: Container(
                    height: double.infinity,
                    width: 110,
                    // color: Colors.red,
                    child: ElevatedButton(
                      onPressed: () {
                        // data[i]['isevaluate']
                        if (data[i]['isevaluate']) {
                          Get.toNamed('/checkscore', arguments: {
                            'group_id': data[i]['id'],
                            'group_sn': data[i]['sn'],
                            'lesson_id': Get.arguments['lesson_id']
                          });
                        } else {
                          // 之所以使用原生跳转 是为了评分后返回能够调用then方法，进行数据更新
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => PhotoPage(arguments: {
                                        'group_id': data[i]['id'],
                                        'group_sn': data[i]['sn'],
                                        'lesson_id': lessonId,
                                        'context':
                                            context // 必须传递本页面context 以便评分成功返回时传递该页面context
                                      }))).then((value) => _load());
                        }
                      },
                      style: ButtonStyle(
                        shape: WidgetStateProperty.all(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(14),
                          ),
                        ), // 去除圆角
                      ),
                      child: Row(
                        children: [
                          Expanded(
                              flex: 1,
                              child: Text(
                                data[i]['tips'],
                                textAlign: TextAlign.center,
                              )),
                          const SizedBox(
                            width: 4,
                            child: Icon(Icons.arrow_right_sharp),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 30,
                  child: ListTile(
                    title: Text(
                        '${StringStyles.createTime.tr}：${data[i]['create_time']}'),
                  ),
                ),
                ListTile(
                  title: Text(
                      '${StringStyles.groupMember.tr}：${data[i]['users']}'),
                ),
              ],
            ),
          ),
          Positioned(
            left: 150,
            top: 40,
            child: data[i]['isevaluate']
                ? JacTag(
                    paddingVertical: 2,
                    paddingHorizontal: 8,
                    tagType: JacTagType.text,
                    tagShapeType: JacTagShapeType.rectangle,
                    tagColorType: JacTagColorType.green,
                    text: StringStyles.scored.tr,
                    fontSize: 12,
                  )
                : const SizedBox(),
          )
        ],
      ));
    }

    return treeList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(taskname),
        backgroundColor: Colors.blue,
      ),
      body: SizedBox(
        height: double.infinity,
        child: isReady
            ? groupList.isEmpty
                ? const EmptyData()
                : ListView(children: loadTaskGroup(groupList))
            : const SizedBox(),
      ),
    );
  }
}
